<template>
  <div class="customer-list-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="渠道名称">
          <el-input v-model="searchForm.channelName" placeholder="请输入渠道名称" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="渠道类型">
          <el-select v-model="searchForm.channelType" placeholder="请选择渠道类型" clearable style="width: 180px">
            <el-option v-for="item in channelTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="当前阶段">
          <el-select v-model="searchForm.currentStage" placeholder="请选择阶段" clearable style="width: 180px">
            <el-option v-for="item in stageOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格工具栏 -->
    <div class="table-toolbar">
      <el-button type="primary" @click="handleAdd">新增销售过程</el-button>
      <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">批量删除</el-button>
      <el-button @click="handleExport">导出</el-button>
    </div>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="employeeId" label="员工编号" width="120" align="center" />
        <el-table-column prop="customerName" label="客户名称" min-width="80" show-overflow-tooltip />
        <el-table-column prop="channelName" label="渠道名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="channelType" label="渠道类型" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getChannelTypeTag(scope.row.channelType)">
              {{ channelTypeFilter(scope.row.channelType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentStage" label="当前阶段" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStageTag(scope.row.currentStage)">
              {{ stageFilter(scope.row.currentStage) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="expectedAmount" label="预计成交金额" width="140" align="right">
          <template #default="scope">
            <span>{{ formatCurrency(scope.row.expectedAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="110" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 销售过程表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增销售过程' : '编辑销售过程'"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="salesOpportunitiesFormRef"
        :model="salesOpportunitiesForm"
        :rules="salesOpportunitiesFormRules"
        label-width="100px"
      >
        <el-form-item label="客户ID" prop="customerId">
          <el-input
            v-model.number="salesOpportunitiesForm.customerId"
            :min="1"
            :precision="0"
            :controls="true"
            style="width: 100%"
            placeholder="请输入客户ID"
          />
        </el-form-item>
        <el-form-item label="渠道ID" prop="channelId">
          <el-input
            v-model.number="salesOpportunitiesForm.channelId"
            :min="1"
            :precision="0"
            :controls="true"
            style="width: 100%"
            placeholder="请输入渠道ID"
          />
        </el-form-item>
        <el-form-item label="员工ID" prop="employeeId">
          <el-input
            v-model.number="salesOpportunitiesForm.employeeId"
            :min="1"
            :precision="0"
            :controls="true"
            style="width: 100%"
            readonly="true"
            placeholder="请输入员工ID"
            :disabled="dialogType === 'add'"
          />
        </el-form-item>
        <el-form-item label="预期金额" prop="expectedAmount">
          <el-input-number
            v-model="salesOpportunitiesForm.expectedAmount"
            :min="0"
            :max="999999999999"
            :precision="2"
            :step="1000"
            :controls="true"
            style="width: 100%"
            placeholder="请输入预期金额"
            :formatter="(value) => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            :parser="(value) => value.replace(/[^\d.]/g, '')"
          />
        </el-form-item>
        <el-form-item label="当前阶段" prop="currentStage">
          <el-select v-model="salesOpportunitiesForm.currentStage" placeholder="请选择阶段" style="width: 100%">
            <el-option v-for="item in stageOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getOpportunitiesList, addOpportunity, updateOpportunity, deleteOpportunities } from "@/api/salesOpportunities";
import { getSaleChanceListExcel } from "@/api/export";

// 渠道类型选项
// 1-线上,2-线下,3-合作伙伴,4-直销,5-代理商
const channelTypeOptions = [
  { value: 1, label: "线上", type: "success" },
  { value: 2, label: "线下", type: "info" },
  { value: 3, label: "合作伙伴", type: "warning" },
  { value: 4, label: "直销", type: "primary" },
  { value: 5, label: "代理商", type: "danger" },
];

// 初步阶段选项
// 1-初步接触,2-需求确认,3-方案制定,4-商务谈判,5-合同签订
const stageOptions = [
  { value: 1, label: "初步接触", type: "info" },
  { value: 2, label: "需求确认", type: "warning" },
  { value: 3, label: "方案制定", type: "primary" },
  { value: 4, label: "商务谈判", type: "success" },
  { value: 5, label: "合同签订", type: "danger" },
];

const channelTypeFilter = (value) => {
  return channelTypeOptions.find((item) => item.value === value)?.label;
};

const stageFilter = (value) => {
  return stageOptions.find((item) => item.value === value)?.label;
};

// 搜索表单
const searchForm = reactive({
  customerName: "",
  channelName: "",
  channelType: "",
  currentStage: "",
});

// 表格数据
const loading = ref(false);
const tableData = ref([]);
const selectedRows = ref([]);

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 对话框
const dialogVisible = ref(false);
const dialogType = ref("add"); // 'add' 或 'edit'
const salesOpportunitiesFormRef = ref(null);
const salesOpportunitiesForm = reactive({
  id: null,
  customerId: null,
  channelId: null,
  expectedAmount: null,
  currentStage: null,
  employeeId: null,
});

// 表单验证规则
const salesOpportunitiesFormRules = {
  customerId: [
    { required: true, message: "请输入客户ID", trigger: "blur" },
    { type: "number", message: "客户ID必须为数字值" },
  ],
  channelId: [
    { required: true, message: "请输入渠道ID", trigger: "blur" },
    { type: "number", message: "渠道ID必须为数字值" },
  ],
  employeeId: [
    { required: true, message: "请输入员工ID", trigger: "blur" },
    { type: "number", message: "员工ID必须为数字值" },
  ],
  expectedAmount: [
    { required: true, message: "请输入预期金额", trigger: "blur" },
    { type: "number", message: "预期金额必须为数字值" },
  ],
  currentStage: [{ required: true, message: "请选择当前阶段", trigger: "change" }],
};

// 初始化
onMounted(() => {
  fetchOpportunitiesList();
});

// 获取销售过程列表
const fetchOpportunitiesList = async () => {
  loading.value = true;
  const response = await getOpportunitiesList({
    ...searchForm,
    current: pagination.currentPage,
    size: pagination.pageSize,
  });

  if (response.success) {
    pagination.total = response.data.total;
    tableData.value = response.data.list;
  } else {
    // 错误消息已由request.js处理
    tableData.value = [];
    pagination.total = 0;
  }
  loading.value = false;
};

// 格式化货币
const formatCurrency = (value) => {
  if (value === undefined || value === null) return "¥0.00";
  return `¥ ${value.toLocaleString("zh-CN", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })}`;
};

// 处理表格选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchOpportunitiesList();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  handleSearch();
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchOpportunitiesList();
};

// 处理当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  fetchOpportunitiesList();
};

// 新增销售过程
const handleAdd = () => {
  dialogType.value = "add";
  dialogVisible.value = true;
  salesOpportunitiesForm.employeeId = 1; // 默认为员工ID默认为1
  resetForm();
};

// 编辑销售过程
const handleEdit = (row) => {
  dialogType.value = "edit";
  dialogVisible.value = true;
  Object.keys(salesOpportunitiesForm).forEach((key) => {
    salesOpportunitiesForm[key] = row[key];
  });
};

// 删除销售过程
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除销售过程 "${row.customerName}" 吗？`, "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await deleteOpportunities([row.id]);
    if (response.success) {
      ElMessage.success("删除成功");
      fetchOpportunitiesList();
    }
    // 错误消息已由request.js处理
  } catch (error) {
    // 这里只处理用户取消操作
    if (error === "cancel") {
      ElMessage.info("已取消删除");
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的销售过程");
    return;
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个销售过程吗？`, "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await deleteOpportunities(selectedRows.value.map((row) => row.id));
    if (response.success) {
      ElMessage.success("批量删除成功");
      fetchOpportunitiesList();
    }
    // 错误消息已由request.js处理
  } catch (error) {
    // 这里只处理用户取消操作
    if (error === "cancel") {
      ElMessage.info("已取消批量删除");
    }
  }
};

// 导出
const handleExport = async () => {
  await getSaleChanceListExcel();
  ElMessage.success("导出成功");
};

// 提交表单
const submitForm = async () => {
  if (!salesOpportunitiesFormRef.value) return;

  const valid = await salesOpportunitiesFormRef.value.validate().catch(() => false);
  if (!valid) return;

  let response;
  if (dialogType.value === "add") {
    response = await addOpportunity(salesOpportunitiesForm);
  } else {
    response = await updateOpportunity(salesOpportunitiesForm);
  }

  if (response.success) {
    ElMessage.success(dialogType.value === "add" ? "新增成功" : "更新成功");
    dialogVisible.value = false;
    fetchOpportunitiesList();
  }
  // 错误消息已由request.js处理
};

// 重置表单
const resetForm = () => {
  if (salesOpportunitiesFormRef.value) {
    salesOpportunitiesFormRef.value.resetFields();
  }

  if (dialogType.value === "add") {
    Object.keys(salesOpportunitiesForm).forEach((key) => {
      if (key === "currentStage") {
        salesOpportunitiesForm[key] = 1;
      } else if (key === "employeeId") {
        salesOpportunitiesForm[key] = 1; // 默认为1
      } else {
        salesOpportunitiesForm[key] = "";
      }
    });
  }
};

// 获取渠道类型标签
const getChannelTypeTag = (value) => {
  const item = channelTypeOptions.find((item) => item.value === value);
  return item ? item.type : "";
};

// 获取阶段标签
const getStageTag = (value) => {
  const item = stageOptions.find((item) => item.value === value);
  return item ? item.type : "";
};
</script>

<style scoped>
.customer-list-container {
  padding: 20px;
  overflow: hidden;
}

.search-card {
  margin-bottom: 20px;
}

.table-toolbar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.table-card {
  margin-bottom: 20px;
  overflow: hidden;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-tag) {
  margin-right: 0;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 20px;
  margin-bottom: 15px;
}

:deep(.el-table) {
  overflow: hidden;
}

:deep(.el-table__body-wrapper) {
  overflow-x: hidden;
}
</style>
